import React, { Component } from 'react';
import './Exam.less'
import GoBack from '../components/GoBack'
import { TimuListApi } from '../request/api'
import Wenda from '../components/exam/Wanda'
import Danxuan from '../components/exam/Danxuan'


// 手指触摸点
let startX = -1;
// 手指松开点
let endX = -1;
// 当前li的索引值
let liIndex = 0;

class Exam extends Component {
  state = {
    timuArr: [{ id: 1, questionType: 'one' },
    { id: 2, questionType: 'qa' },
    { id: 3, questionType: 'one' },
    { id: 4, questionType: 'qa' },
    { id: 5, questionType: 'one' },
    { id: 6, questionType: 'qa' },
    { id: 7, questionType: 'one' },
    { id: 8, questionType: 'qa' },
    { id: 9, questionType: 'one' },

    ],
    ulLeft: 0
  }
  // 卸载函数生命周期
  componentWillUnmount() {
    startX = -1;
    endX = -1;
    liIndex = 0;
  }
  componentDidMount() {
    TimuListApi(this.props.location.state).then(res => {
      console.log(res)
      if (res.errCode === 0) {
        this.setState({ timuArr: res.data })
      }
    }).catch(res => {
      console.log('错误信息', res)
    })
  }
  render() {
    return (
      <div className='exam-page'>
        <div className="top-da">
          <i className='iconfont icon-calculator' />
          {/* section是行内块元素 */}
          <section>
            {/* <small></small>小一点点，big是字体大一点点 Math.abs()是绝对值*/}
            <big>{Math.abs(liIndex) + 1}</big>
            <span>/{this.state.timuArr.length}</span>
          </section>
        </div>
        <ul className='ul-list' style={{ width: this.state.timuArr.length * 100 + '%', left: this.state.ulLeft }} onTouchStart={this.handleTouchStart.bind(this)}
          onTouchMove={this.handleTouchMove.bind(this)}
          onTouchEnd={this.handleTouchEnd.bind(this)}>
          {this.state.timuArr.map((item) => (
            <li key={item.id} className='ul-list-li'>
              {/* 单选组件 */}
              <Danxuan type={item.questionType} />
              {/* 问答 */}
              <Wenda type={item.questionType} />
            </li>
          ))}
        </ul>
        {/* 返回按钮组件 */}
        <GoBack />
      </div>
    );
  }
  // 手指触摸到屏幕
  handleTouchStart(e) {
    startX = e.touches[0].clientX
  }
  // 手指滑动
  handleTouchMove(e) {
    endX = e.touches[0].clientX
  }
  // 手指离开屏幕
  handleTouchEnd(e) {
    let _this = this;
    // 获取滑动范围
    if (startX > -1 && endX > -1) {
      let distance = Math.abs(startX - endX);
      if (distance > 50) {
        // 两个手指位置距离相差50px，即视为要滑动
        if (startX > endX) {
          liIndex--;
          // index是不能超过数组长度的
          if (Math.abs(liIndex) >= _this.state.timuArr.length - 1) {
            liIndex = -_this.state.timuArr.length + 1;
          }
        } else {
          liIndex++;
          if (liIndex >= 0) {
            liIndex = 0;
          }
        }
        this.setState({ ulLeft: 100 * liIndex + '%' }, () => {
          startX = -1;
          endX = -1;
        });
      } else {
        return;
      }
    }
  }
}

export default Exam;